package com.ruoyi.gouhuoruku.controller;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.cangku.service.ICangkuService;
import com.ruoyi.kucunpandian.domain.Kucunpandian;
import com.ruoyi.shangpinxinxi.domain.TestResult;
import com.ruoyi.kucunpandian.service.IKucunpandianService;
import com.ruoyi.piliangruku.service.IPiliangRukuService;
import com.ruoyi.shangpinxinxi.service.IShangpinxinxiService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.gouhuoruku.domain.GouhuoRuku;
import com.ruoyi.gouhuoruku.service.IGouhuoRukuService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 购货入库Controller
 * 
 * @author ruoyi
 * @date 2023-01-10
 */
@Controller
@RequestMapping("/gouhuoruku/rukuTest")
public class GouhuoRukuController extends BaseController
{
    private String prefix = "gouhuoruku/rukuTest";

    @Autowired
    private IGouhuoRukuService gouhuoRukuService;
    @Autowired
    private IKucunpandianService cangkupandianService;
    @Autowired
    private IPiliangRukuService piliangRukuService;
    @Resource
    private IShangpinxinxiService shangpinxinxiService;
    @Autowired
    private ICangkuService cangkuService;

    @RequiresPermissions("gouhuoruku:rukuTest:view")
    @GetMapping()
    public String rukuTest()
    {
        return prefix + "/rukuTest";
    }

    /**
     * 查询购货入库列表
     */
    @RequiresPermissions("gouhuoruku:rukuTest:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GouhuoRuku gouhuoRuku)
    {
        startPage();
        List<GouhuoRuku> list = gouhuoRukuService.selectGouhuoRukuList(gouhuoRuku);
        return getDataTable(list);
    }

    /**
     * 导出购货入库列表
     */
    @RequiresPermissions("gouhuoruku:rukuTest:export")
    @Log(title = "购货入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GouhuoRuku gouhuoRuku)
    {
        List<GouhuoRuku> list = gouhuoRukuService.selectGouhuoRukuList(gouhuoRuku);
        ExcelUtil<GouhuoRuku> util = new ExcelUtil<GouhuoRuku>(GouhuoRuku.class);
        return util.exportExcel(list, "购货入库数据");
    }

    /**
     * 新增购货入库
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:add")
    @Log(title = "购货入库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GouhuoRuku gouhuoRuku)
    {
        TestResult testResult = new TestResult();
        testResult.setMenName(gouhuoRuku.getShangpinName());
        testResult.setMenKuan(gouhuoRuku.getGuiGeKuan());
        testResult.setMenGao(gouhuoRuku.getGuiGeGao());
        testResult.setKaiXiang(gouhuoRuku.getKaiXiang());
        Kucunpandian kucunpandian = cangkupandianService.selectKucunpandianByNameAndSize(testResult);

        if (kucunpandian == null) {
            return toAjax("新增的商品不存在");
        }

        long newkucun = kucunpandian.getKuncun()+Long.parseLong(gouhuoRuku.getShuLiang());
        kucunpandian.setKuncun(newkucun);

        cangkupandianService.updateKucunpandian(kucunpandian);

        return toAjax(gouhuoRukuService.insertGouhuoRuku(gouhuoRuku));
    }

    /**
     * 修改购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        GouhuoRuku gouhuoRuku = gouhuoRukuService.selectGouhuoRukuById(id);
        mmap.put("gouhuoRuku", gouhuoRuku);
        return prefix + "/edit";
    }

    /**
     * 修改保存购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:edit")
    @Log(title = "购货入库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GouhuoRuku gouhuoRuku)
    {
        TestResult testResult = new TestResult();
        testResult.setMenName(gouhuoRuku.getShangpinName());
        testResult.setMenKuan(gouhuoRuku.getGuiGeKuan());
        testResult.setMenGao(gouhuoRuku.getGuiGeGao());
        testResult.setKaiXiang(gouhuoRuku.getKaiXiang());
        Kucunpandian kucunpandian = cangkupandianService.selectKucunpandianByNameAndSize(testResult);

        GouhuoRuku old = gouhuoRukuService.selectGouhuoRukuById(gouhuoRuku.getId());

        long newkucun = kucunpandian.getKuncun()+Long.parseLong(gouhuoRuku.getShuLiang())-Long.parseLong(old.getShuLiang());
        kucunpandian.setKuncun(newkucun);

        cangkupandianService.updateKucunpandian(kucunpandian);

        return toAjax(gouhuoRukuService.updateGouhuoRuku(gouhuoRuku));
    }

    /**
     * 删除购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:remove")
    @Log(title = "购货入库", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        GouhuoRuku gouhuoRuku = gouhuoRukuService.selectGouhuoRukuById(Long.valueOf(ids));
        TestResult testResult = new TestResult();
        testResult.setMenName(gouhuoRuku.getShangpinName());
        testResult.setLeibie(gouhuoRuku.getShangpinLeibie());
        testResult.setMenKuan(gouhuoRuku.getGuiGeKuan());
        testResult.setMenGao(gouhuoRuku.getGuiGeGao());
        testResult.setKaiXiang(gouhuoRuku.getKaiXiang());
        Kucunpandian kucunpandian = cangkupandianService.selectKucunpandianByNameAndSize2(testResult);
        if (kucunpandian == null) {
            return toAjax("未找到该入库商品的库存");
        }
        kucunpandian.setKuncun(kucunpandian.getKuncun()-Long.parseLong(gouhuoRuku.getShuLiang()));
        cangkupandianService.updateKucunpandian(kucunpandian);
        return toAjax(gouhuoRukuService.deleteGouhuoRukuByIds(ids));
    }

    /**
     * 批量增加购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:inserts")
    @Log(title = "购货入库", businessType = BusinessType.INSERT)
    @PostMapping("/inserts")
    @ResponseBody
    public AjaxResult inserts(String msg) {
        List<GouhuoRuku> gouhuoRukuList = new ArrayList<>();
        List<String> danhaoList = new ArrayList<>();
        List<String> piliangdanhaoList = new ArrayList<>();
        int bo = 0;
        if (msg.lastIndexOf("@", 7) != -1) {
            String[] goho = msg.split("@");
            String danhaoStr = gouhuoRukuService.selectGouhuoDanhaoByLastOne();
            for (int i = 0; i < goho.length-1; i++) {
                if (danhaoStr == null||danhaoStr.equals("")) {
                    if (i == 0) {
                        String danhao = "00000001";
                        danhaoList.add(danhao);
                    }else {
                        String danhao2Str = danhaoList.get(i-1);
                        danHaoSet(danhao2Str, danhaoList);
                    }
                }else {
                    if (i == 0) {
                        danHaoSet(danhaoStr, danhaoList);
                    }else {
                        String danhao2Str = danhaoList.get(i-1);
                        danHaoSet(danhao2Str, danhaoList);
                    }
                }
            }

            for (int i = 1; i < goho.length; i++) {
                msgChongZu(goho[i], gouhuoRukuList,danhaoList.get(i-1),piliangdanhaoList);
            }
        } else {
            String danhaoStr = gouhuoRukuService.selectGouhuoDanhaoByLastOne();
            danHaoSet(danhaoStr, danhaoList);
            msgChongZu(msg, gouhuoRukuList, danhaoList.get(0),piliangdanhaoList);
        }
        for (int i = 0; i < gouhuoRukuList.size(); i++) {
            if (gouhuoRukuList.get(i) != null) {
                bo = gouhuoRukuService.insertGouhuoRuku(gouhuoRukuList.get(i));
                kucunMoreSet(gouhuoRukuList.get(i));
                piliangRukuService.deletePiliangRukuByGgouhuoDanhao(piliangdanhaoList.get(i));
            }
        }
        if (bo != -1) {
            return toAjax(bo);
        } else {
            return toAjax(-1);
        }
    }

    private static void danHaoSet(String danhaoStr, List<String> danhaoList) {
        int num = Integer.parseInt(danhaoStr)+1;
        String b = String.valueOf(num);
        if (b.length() < 8) {
            int a = 8-b.length();
            for (int j = 0; j < a; j++) {
                b="0"+b;
            }
        }
        danhaoList.add(b);
    }

    private static void msgChongZu(String msg, List<GouhuoRuku> gouhuoRukuList,String danhao,List<String> piiangdanhao) {
        try {
            if (msg.length() >= 1) {
                String[] msgs = msg.split("：");
                String fid = msgs[1].split("；")[0];
                piiangdanhao.add(fid);
                Date fDate = new SimpleDateFormat("yyyy-MM-dd").parse(
                        msgs[2].split("；")[0]);
                String frukuMen = msgs[3].split("；")[0];
                String fshangpinName = msgs[4].split("；")[0];
                String ftupian = msgs[5].split("；")[0];
                String fleibie = msgs[6].split("；")[0];
                String fguiGeKuan = msgs[7].split("；")[0];
                String fguiGeGao = msgs[8].split("；")[0];
                String fkaiXiang = msgs[9].split("；")[0];
                String fshuLiang = msgs[10].split("；")[0];
                String fdanJia = msgs[11].split("；")[0];
                double fzongjine = Double.parseDouble(msgs[12].split("；")[0]);
                String GShangpinBeiZhu = "";
                if (msgs[13].length() <=1) {
                    GShangpinBeiZhu = null;
                }else {
                    GShangpinBeiZhu = msgs[13].split("；")[0];
                }


                GouhuoRuku gouhuoRuku = new GouhuoRuku();

                gouhuoRuku.setGouhuoDanhao(danhao);
                gouhuoRuku.setChukuDate(fDate);
                gouhuoRuku.setShangpinName(fshangpinName);
                gouhuoRuku.setTupian(ftupian);
                gouhuoRuku.setShangpinLeibie(fleibie);
                gouhuoRuku.setGuiGeKuan(fguiGeKuan);
                gouhuoRuku.setGuiGeGao(fguiGeGao);
                gouhuoRuku.setKaiXiang(String.valueOf(fkaiXiang));
                gouhuoRuku.setShuLiang(fshuLiang);
                gouhuoRuku.setDanJia(String.valueOf(fdanJia));
                gouhuoRuku.setZongjine(BigDecimal.valueOf(fzongjine));
                gouhuoRuku.setRukuMen(frukuMen);
                gouhuoRuku.setBeizhu(GShangpinBeiZhu);


                gouhuoRukuList.add(gouhuoRuku);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void kucunMoreSet(GouhuoRuku go) {
        TestResult testResult = new TestResult();
        testResult.setMenName(go.getShangpinName());
        testResult.setMenKuan(go.getGuiGeKuan());
        testResult.setMenGao(go.getGuiGeGao());
        testResult.setKaiXiang(go.getKaiXiang());
        Kucunpandian kucunpandian = cangkupandianService.selectKucunpandianByNameAndSize2(testResult);
        if (kucunpandian != null) {
            Long kucun = kucunpandian.getKuncun();

            double newKuCun = kucun+Double.parseDouble(go.getShuLiang());

            kucunpandian.setKuncun(new Double(newKuCun).longValue());
            cangkupandianService.updateKucunpandian(kucunpandian);
        }else {
            Kucunpandian kucunpandianNew = new Kucunpandian();
            kucunpandianNew.setGoodName(go.getShangpinName());
            kucunpandianNew.setShangpinLeibie(go.getShangpinLeibie());
            kucunpandianNew.setShangpinTuPian(go.getTupian());
            kucunpandianNew.setShangpinGuigeKuan(go.getGuiGeKuan());
            kucunpandianNew.setShangpinGuigeGao(go.getGuiGeGao());
            kucunpandianNew.setShangpinKaixiang(go.getKaiXiang());
            kucunpandianNew.setKuncun(Long.parseLong(go.getShuLiang()));
            cangkupandianService.insertKucunpandian(kucunpandianNew);
        }
    }
}
